package com.fwtai.service.web;

import com.fwtai.bean.PageFormData;
import com.fwtai.tool.IdBuilder;
import com.fwtai.tool.ToolClient;
import com.fwtai.web.ConversionDao;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * 积分兑换记录业务层
 * @作者 田应平
 * @版本 v1.0
 * @QQ号码 444141300
 * @创建日期 2023-04-19 10:20:18
 * @官网 <url>http://www.fwtai.com</url>
*/
@Service
public class ConversionService{

  private final ConversionDao conversionDao;

  private final ThreadPoolTaskExecutor taskExecutor;

  public ConversionService(final ConversionDao conversionDao,final ThreadPoolTaskExecutor taskExecutor){
    this.conversionDao = conversionDao;
    this.taskExecutor = taskExecutor;
  }

  public String editBatchAudit(final String kid,final Integer audit_status,final String total,final String comment,final String user_id){
    return CompletableFuture.supplyAsync(()->{
      if(kid == null || audit_status == null || user_id == null || total == null){
        return ToolClient.jsonValidateField();
      }
      final PageFormData params = new PageFormData(4);
      final long userId = Long.parseLong(user_id);
      final long outId = Long.parseLong(kid);
      params.put("kid",outId);
      params.put("audit_status",audit_status);
      params.put("user_id",userId);
      if(comment != null && comment.length() > 0){
        params.put("comment",comment);
      }
      final HashMap<String,Object> account_out = new HashMap<>(3);
      account_out.put("kid",new IdBuilder().getId121L());
      account_out.put("user_id",userId);
      account_out.put("score",new BigDecimal(total));
      account_out.put("out_id",outId);
      if(audit_status == 2){
        return ToolClient.executeRows(conversionDao.editBatchAudit(params,account_out),"操作成功","操作失败");
      }else{
        return ToolClient.executeRows(conversionDao.editBatchAudit(params),"操作成功","操作失败");
      }
    },taskExecutor).join();
  }

  public String listData(final PageFormData formData){
    return CompletableFuture.supplyAsync(()->{
      try{
        if(ToolClient.dataTableMysql(formData) == null) return ToolClient.jsonValidateField();
        final CompletableFuture<List<HashMap<String,Object>>> listData = CompletableFuture.supplyAsync(() -> conversionDao.getListData(formData),taskExecutor);
        final CompletableFuture<Integer> listTotal = CompletableFuture.supplyAsync(() -> conversionDao.getListTotal(formData),taskExecutor);
        return ToolClient.dataTableOK(listData.join(),listTotal.join());
      } catch (final Exception ignored){
        return ToolClient.dataTableException();
      }
    },taskExecutor).join();
  }
}